<?php
/**
 * @package   nuo.view
 * @author    Nam Nguyen
 * @version   1.0
 * @since     Apr 14, 2013
 */
class Nuo_View
{

	/**
	 * Storage find script paths
	 * @access  public
	 * @var array
	 */
	protected $_paths = array(MODULE_DIR);

	/**
	 * @param string $path
	 * @return void
	 */
	public function addPath($path)
	{
		array_unshift($this -> _paths, $path);
	}

	/**
	 * Find a script path in full path
	 *
	 * @access  public
	 * @param   string  $script
	 * @return  string
	 * Return Null if not found
	 */
	public function find($script)
	{
		$script .= '.html.php';

		foreach ($this->_paths as $path)
		{
			if (file_exists($path . '/' . $script))
			{
				return $path . '/' . $script;
			}
		}
		return NULL;
	}

	/**
	 * escape string
	 * @param string $string
	 * @return string
	 */
	public function escape($string)
	{
		return htmlspecialchars($string, ENT_COMPAT, NUO_CHARSET);
	}

	/**
	 * process render
	 * @param string $script
	 * @param array $data
	 * @param bool $find
	 * @return string
	 */
	public function render($script, $data = array(), $find = TRUE)
	{
		ob_start();

		$__SCRIPT__ = self::find($script, $find);

		if (!$__SCRIPT__)
		{
			trigger_error("$script not found in view paths.", E_USER_WARNING);
		}
		else
		{
			extract($data, EXTR_SKIP);

			include $__SCRIPT__;
		}
		return ob_get_clean();
	}

	/**
	 * @param string $msg
	 * @return string
	 */
	public function filterOutput($msg)
	{
		$msg = nl2br($msg);
		return preg_replace("#@\[(\w+).(\d+):([^\]]+)\]#i", "<a href=\"#\">$3</a>", $msg);
	}

	/**
	 * @static
	 * @access  public
	 * @param   string  $name
	 * @param   array   $params Optinal
	 * @return  string
	 */
	public function renderWidget($name, $params = array())
	{
		$cls = inflect($name);

		if (Nuo::loadModuleClass($cls))
		{
			$widget = new $cls($params);
			return $widget -> execute();
		}
		return '';
	}
}
